/**
 * udp 广播客户端，发送端
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
    if (3 > argc)
    {
        fprintf(stderr, "%s <server_ip|server_hostname> <server_port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (0 > socket)
    {
        perror("socket error: ");
        exit(EXIT_FAILURE);
    }

    int opt = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(int)) < 0)
    {
        perror("setsockopt error: ");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);

    socklen_t addrlen = sizeof(struct sockaddr_in);

    while (1)
    {

        char buf[1024] = {0};
        printf("> ");
        scanf("%s", buf);

        if (buf[0] == 'q' || buf[0] == 'Q')
        {
            break;
        }

        if (sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serverAddr, addrlen) <= 0)
        {
            break;
        }
    }

    close(sockfd);

    return 0;
}